package com.eunion.web.common.base;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.eunion.core.exception.ValidateException;

/**
 * Asset基类，提供一些基本变量
 */
public abstract class BaseAssetController {

    /**
     * 日志 子类也可用 .
     */
    protected Logger LOG = LoggerFactory.getLogger(getClass());

    /**
     * 获取当前请求request.
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取当前请求session.
     */
    protected HttpSession getSession() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
    }

    @ModelAttribute
    public void populateModel(Model model) {
        model.addAttribute("reqUrl", getRequest().getRequestURI());
    }

    /**
     * 检查bindingresult中是否有异常.
     * @throws ValidateException 验证的异常.
     */
    protected void checkBindResult(BindingResult result) {
        // ObjectValidator.validate(obj); //使用这句配置catch模块也可以完成验证
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                if (StringUtils.isNotEmpty(error.getDefaultMessage())) {
                    throw new ValidateException(error.getDefaultMessage());
                }
            }
        }
    }

    /**
     * 判断是数字包括小数
     * @param str
     * @return
     */
    protected static boolean isNumber(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (Exception e) {}
        try {
            Double.parseDouble(str);
            return true;
        } catch (Exception e) {}
        return false;
    }
}
